#!/bin/bash

## 环境配置
HADOOP_HOME=/opt/apps/hadoop
HIVE_HOME=/opt/apps/hive


## 获取当前日期和前一天
target_dt=$(date -d'-1 day' +'%Y-%m-%d')
target_pre_dt=$(date -d'-2 day' +'%Y-%m-%d')


if [ $1 ]
then
  target_dt=$1
  target_pre_dt=$(date -d"$1 -1 day" +'%Y-%m-%d')
fi

echo "要计算的目标日期是: $target_dt "

sql="
with pre_day_bind_table as (select device_id,
                                   user_name,
                                   bind_weight,
                                   last_login_time
                            from dim.device_username_bind
                            where dt = '${target_pre_dt}')

   , cur_day_tuple as (SELECT username            as user_name,
                              device_id,
                              cast(100 as double) as bind_weight,
                              max(action_time)    as last_login_time
                       FROM ods.user_action_log
                       where dt = '${target_dt}'
                         and username is not null
                         and trim(username) != ''
                       group by username, device_id)


insert into dim.device_username_bind partition(dt='${target_dt}')
select nvl(a.device_id, b.device_id)             as device_id,
       nvl(a.user_name, b.user_name)             as user_name,
       case
           when a.device_id is not null and b.device_id is not null then a.bind_weight + b.bind_weight
           when a.device_id is not null and b.device_id is null then a.bind_weight * 0.25
           else b.bind_weight
           end                                   as bind_weight,
       nvl(b.last_login_time, a.last_login_time) as last_login_time

from pre_day_bind_table a
         full join cur_day_tuple b
                   on a.device_id = b.device_id and a.user_name = b.user_name

"


# 执行sql
${HIVE_HOME}/bin/hive -e "$sql"

if [ $? -eq 0 ]
then
  echo "计算任务完成"
  exit 0
  else
    echo "计算任务失败"
    exit 1
fi